package mapspinner;

import com.jme.math.Vector3f;
import com.jme.scene.TriMesh;

public class TerrainMesh extends TriMesh {
	/**
	 * This extends the normal jme trimesh class in order to replace accesses to
	 * the y vertex coordinate and map it to the vertex color buffer, this is
	 * important for maintaining a small memory footprint since vertex
	 * coordinates can then be shared by all terrain trimeshes.
	 */
	private static final long serialVersionUID = 525715072923442716L;

	public TerrainMesh(final String name) {
		super(name);
	}

	public float getColor(final int index, final int layer) {
		return colorBuf.get(index * 4 + layer);
	}

	/**
	 * We have to get triangle information in a different manner from TriMesh,
	 * since x and z is shared among all nodes, and y is stored in the color
	 * buffer's alpha.
	 */
	@Override
	public void getTriangle(final int i, Vector3f[] vertices) {
		if (vertices == null)
			vertices = new Vector3f[3];
		if (i < getTriangleCount() && i >= 0)
			for (int x = 0; x < 3; x++) {
				if (vertices[x] == null)
					vertices[x] = new Vector3f();

				vertices[x].set(vertBuf.get(getIndexBuffer().get(
						getVertIndex(i, x)) * 3), colorBuf.get(getIndexBuffer()
						.get(getVertIndex(i, x)) * 4 + 3), vertBuf
						.get(getIndexBuffer().get(getVertIndex(i, x)) * 3 + 2));
			}
	}

	public void setColor(final int index, final int layer, final float value) {
		colorBuf.put(index * 4 + layer, value);
	}
}
